package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xsz
 * @DateTime: 2024/2/17 14:33
 **/

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {


    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 生成静态文件上传到MinIO中
     *
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {


        if (StringUtils.isNotBlank(content)) {
            //把文章内容通过freemarker生成HTML文件
            StringWriter out = new StringWriter();
            Template template = null;
            try {
                template = configuration.getTemplate("article.ftl");
                Map<String, Object> params = new HashMap<>();
                params.put("content", JSONArray.parseArray(content));
                template.process(params, out);

            } catch (IOException | TemplateException e) {
                e.printStackTrace();
            }

            //out中的内容转换为字节数组，并通过 ByteArrayInputStream 创建一个输入流 is。
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            //把html文件上传到minion中
            String s = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);

            //修改ap_article表，保存static_url字段
            ApArticle apArticleResult = new ApArticle();
            apArticleResult.setId(apArticle.getId());
            apArticleResult.setStaticUrl(s);
            apArticleMapper.updateById(apArticleResult);
        }
    }
}
